import { Injectable, ElementRef, Renderer2 } from '@angular/core';


@Injectable()
export class AppWindow {

  getGlobalObject(): any {
    return window;
  }


  getOwnerDocument(elmRef?: ElementRef): Document {
    return elmRef ? elmRef.nativeElement.ownerDocument : window.document;
  }

  scrollTo(selector: string, elmRef?: ElementRef): AppWindow {
    const elm: any = this.getOwnerDocument(elmRef).querySelector(selector);
    elm.scrollIntoView();
    return this;
  }

  scrollToTop(elmRef?: ElementRef): AppWindow {
    this.getOwnerDocument(elmRef).body.scrollIntoView();
    return this;
  }

  createScript(src: string, renderer: Renderer2, elmRef?: ElementRef, callback?: Function): HTMLScriptElement {
    const script = elmRef ? renderer.createElement('script') :
      this.getOwnerDocument().createElement('script');

    script.type = 'text/javascript';
    script.src = src;
    //规定异步加载   defer页面已加载后才会运行脚本
    script.async = true;
    script.charset = 'UTF-8';
    script.id = `${new Date()}`;

    if (callback) {
      //IE的 script 元素支持onreadystatechange事件，不支持onload事件。
      //FF的script 元素不支持onreadystatechange事件，只支持onload事件。
//       readyState 属性返回当前文档的状态（载入中……）。

// 该属性返回以下值:

//     uninitialized - 还未开始载入
//     loading - 载入中
//     interactive - 已加载，文档与用户可以开始交互
//     complete - 载入完成
      script.onreadystatechange = script.onload = () => {
        //正则匹配readyState属性
        if ((!script.readyState || /loaded|complete/.test(script.readyState))) {
          console.log((!script.readyState || /loaded|complete/.test(script.readyState)));
          callback();
        }
      };
    }
    renderer.appendChild(elmRef.nativeElement, script);
    return script;
  }

}
